package com.zyz.minio.service;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;


@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    public void bucketIsExists() throws Exception {
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket("mybucket").build());
        System.out.println("bucketExists = " + bucketExists);
    }

    public void createBucket() throws Exception {
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket("mybucket").build());
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket("mybucket").build());
            System.out.println("bucket创建成功");
        }

    }

    public void removeBucket() throws Exception {
        // 删除bucket
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket("mybucket").build());
        System.out.println("bucket删除成功");
    }

    public void putObject() throws Exception {
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket("mybucket").build());
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket("mybucket").build());
            System.out.println("bucket创建成功");
        }
        File file = new File("C:\\Users\\30996\\Desktop\\b_6dc84927ede1873582617ee97f420baa.jpg");
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket("mybucket")
                .object("test.png")
                .stream(new FileInputStream(file), file.length(), -1)
                .build());
        System.out.println("objectWriteResponse.etag() = " + objectWriteResponse.etag());
        System.out.println("objectWriteResponse.versionId() = " + objectWriteResponse.versionId());
        System.out.println("objectWriteResponse.bucket() = " + objectWriteResponse.bucket());
        System.out.println("objectWriteResponse.headers() = " + objectWriteResponse.headers());
        System.out.println("objectWriteResponse.object() = " + objectWriteResponse.object());
        System.out.println("objectWriteResponse.region() = " + objectWriteResponse.region());
    }

    public void uploadObject() throws Exception {
        File file = new File("C:\\Users\\30996\\Desktop\\b_6dc84927ede1873582617ee97f420baa.jpg");
        ObjectWriteResponse uploadObject = minioClient.uploadObject(UploadObjectArgs.builder()
                .bucket("mybucket")
                .object("test2.png")
                .filename("C:\\Users\\30996\\Desktop\\b_6dc84927ede1873582617ee97f420baa.jpg")
                .build());
        System.out.println("uploadObject.versionId() = " + uploadObject.versionId());
        System.out.println("uploadObject.object() = " + uploadObject.object());
    }

    public void statObject() throws Exception {
        StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs
                .builder()
                .bucket("mybucket")
                .object("test2.png")
                .build());
        System.out.println("statObjectResponse.lastModified() = " + statObjectResponse
                .lastModified()
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println("statObjectResponse.size() = " + statObjectResponse.size());
    }

    public void getFileUrl() throws Exception {
        String objectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket("mybucket")
                .object("test.png")
                .method(Method.GET)
                .expiry(20, TimeUnit.SECONDS)
                .build());
        System.out.println("objectUrl = " + objectUrl);
    }

    public void setBucketPolicy() throws Exception {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket("mybucket2").build())) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket("mybucket2")
                    .build());
        }
        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                .bucket("mybucket2")
                .config("{\n" +
                        "    \"Version\": \"2012-10-17\",\n" +
                        "    \"Statement\": [\n" +
                        "        {\n" +
                        "            \"Effect\": \"Allow\",\n" +
                        "            \"Principal\": {\n" +
                        "                \"AWS\": [\n" +
                        "                    \"*\"\n" +
                        "                ]\n" +
                        "            },\n" +
                        "            \"Action\": [\n" +
                        "                \"s3:GetObject\"\n" +
                        "            ],\n" +
                        "            \"Resource\": [\n" +
                        "                \"arn:aws:s3:::mybucket2/*\"\n" +
                        "            ]\n" +
                        "        },\n" +
                        "        {\n" +
                        "            \"Effect\": \"Deny\",\n" +
                        "            \"Principal\": {\n" +
                        "                \"AWS\": [\n" +
                        "                    \"*\"\n" +
                        "                ]\n" +
                        "            },\n" +
                        "            \"Action\": [\n" +
                        "                \"s3:DeleteObject\",\n" +
                        "                \"s3:PutObject\"\n" +
                        "            ],\n" +
                        "            \"Resource\": [\n" +
                        "                \"arn:aws:s3:::mybucket2/*\"\n" +
                        "            ]\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}")
                .build());
    }

    /**
     * 文件下载 方法1（推荐）
     *
     * @throws Exception
     */
    public void getObject() throws Exception {
        GetObjectResponse getObjectResponse = minioClient.getObject(GetObjectArgs.builder()
                .bucket("mybucket")
                .object("test.png")
                .build());
        String fileName = getObjectResponse.object();
        String path = "./" + fileName;

        long transferTo = getObjectResponse.transferTo(new FileOutputStream(path));
        System.out.println("transferTo = " + transferTo);
        System.out.println("getObjectResponse.object() = " + getObjectResponse.object());
    }

    /**
     * 文件下载 方法2
     * @throws Exception
     */
    public void getObject2() throws Exception {
        GetObjectResponse getObjectResponse = minioClient.getObject(GetObjectArgs.builder()
                .bucket("mybucket")
                .object("test.png")
                .build());
        String fileName = getObjectResponse.object();
        String path = "./" + fileName;
        byte[] bytes = new byte[1024];
        try(FileOutputStream fileOutputStream = new FileOutputStream(path)) {
            int bytesRead = 0;
            while ((bytesRead = getObjectResponse.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, bytesRead);
            }
        }
        System.out.println("文件下载完毕");
    }

    public void listObject() throws Exception{
        Iterable<Result<Item>> mybucketObjects = minioClient.listObjects(ListObjectsArgs.builder()
                .bucket("mybucket")
                .build());
        for (Result<Item> i : mybucketObjects) {
            System.out.println("i.get().objectName() = " + i.get().objectName());
        }
    }

    public void removeObject() throws Exception{
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket("mybucket")
                .object("test.png")
                .build());
        System.out.println("删除object成功");
    }

}
